package com.pt25.base.dep.log;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class LogAspect {
    @Around("@annotation(com.pt25.base.dep.log.Log)")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取注解信息
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Log logObj = signature.getMethod().getAnnotation(Log.class);
        // 获取方法名
        String methodName = joinPoint.getSignature().getName();
        // 获取方法入参
        Object[] args = joinPoint.getArgs();
        StringBuilder argsString = new StringBuilder();
        for (Object arg : args) {
            argsString.append(arg).append(",");
        }
        if (!argsString.isEmpty()) {
            argsString.deleteCharAt(argsString.length() - 1); // 删除最后一个逗号
        }
        // 打印方法入参
        log.info("{}{}-parameters:{}", logObj.value(), methodName, argsString);
        // 执行目标方法
        Object result = joinPoint.proceed();
        // 打印方法返回值
        log.info("{}{}-returned:{}", logObj.value(), methodName, result);
        return result;
    }
}
